package com.zcw.rabbitmq.chatroom;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.zcw.rabbitmq.util.RabbitConnectionUtil;

import java.io.IOException;

/**
 * 群聊发布订阅类
 */
public class ChatRoomPublisher {
    public final static String EXCHANGE_NAME = "chat_room_exchange";

    public static void sendMesage(String mesage){
        try {
            Connection connection = RabbitConnectionUtil.getSingleRabbitConnection();
            Channel channel = connection.createChannel();
            // 声明交换机
            channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.FANOUT);

            // 声明队列MEBER_QUEUE_NAME1
            channel.queueDeclare(RabbitConnectionUtil.MEBER_QUEUE_NAME1, true, false, false, null);
            // 将队列MEBER_QUEUE_NAME1与交换机EXCHANGE_NAME进行绑定
            channel.queueBind(RabbitConnectionUtil.MEBER_QUEUE_NAME1, EXCHANGE_NAME,"");

            // 声明队列MEBER_QUEUE_NAME2
            channel.queueDeclare(RabbitConnectionUtil.MEBER_QUEUE_NAME2, true, false, false, null);
            // 将队列MEBER_QUEUE_NAME2与EXCHANGE_NAME进行绑定
            channel.queueBind(RabbitConnectionUtil.MEBER_QUEUE_NAME2,EXCHANGE_NAME,"");

            // 发送消息
            channel.basicPublish(EXCHANGE_NAME, "", null, mesage.getBytes("UTF-8"));
            System.out.println("消息：'" + mesage + "'发送成功！");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
